package com.example.tossednfound;


import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
public class LoginActivity extends Activity {
	/**
	 * A dummy authentication store containing known user names and passwords.
	 * TODO: remove after connecting to a real authentication system.
	 */
	private RegUser dummyUser;
	private AdminUser dummyAdmin;
	private Item dummyItem;
	public static ArrayList<RegUser> UserList;
	public static ArrayList<AdminUser> AdminList;
	public static ArrayList<Item> ItemList;
	public static Item currentItem;
	public static User loggedIn;
	public boolean beenCreated;
	/**
	 * The default email to populate the email field with.
	 */
	public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";

	/**
	 * Keep track of the login task to ensure we can cancel it if requested.
	 */
	private UserLoginTask mAuthTask = null;

	// Values for email and password at the time of the login attempt.
	private String mEmail;
	private String mPassword;

	// Database 
	//private Context context = this;

	// UI references.
	private EditText mEmailView;
	private EditText mPasswordView;
	private View mLoginFormView;
	private View mLoginStatusView;
	private TextView mLoginStatusMessageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dummyUser = new RegUser("foo@example.com", "hello", "a", "b", 0, "c", "foo");
		RegUser otherUser = new RegUser("user@user.com", "hello", "a", "b",0, "c", "user");
		dummyAdmin = new AdminUser("admin@admin.com", "admin", "a", "b", 3, "c", "admin");
		
	//public Item(String creator, int rewardAmt, String category,
	//	 String tags, String createdDate, String itemName,
	//	int entryType, String description, String state, String zipCode,
	//	String streetAddress, String country) {

		Item dummyItem0 = new Item("JAMES", 50, "Keepsake", "yellow, toy, child", "1-3-2012", 
				"TEDDY BEAR", 0, "This is a fluffy yellow teddy bear. It was lost during a tornado.", 
				"Georgia", "30005", "4923 Bluejay Ln, Marietta", "USA");
		Item dummyItem1 = new Item("TOMMY", 25, "Heirloom", "clock, tornado, wood, silver",
				"12-11-2003", "CLOCK", 1, "A small, wooden table clock I inherited from my grandmother." +
				" The hands of the face are silver.", "Connecticut", "19443", 
				"12 Flower Street, Bridgeport", "USA");
		Item dummyItem2 = new Item("SALLY", 1500, "Heirloom", "expensive, jewelry, necklace, silver, " +
				"diamond, shiny", "5-25-2007", "DIAMOND NECKLACE", 1, "A large diamond on a thin silver " +
				"chain.", "Texas", "54301", "4080 Ranch Avenue, Austin", "USA");
		Item dummyItem3 = new Item("AMBER", "BAND-AIDS", 2, "3-12-2013", "Misc");
		Item dummyItem4 = new Item("OLD MAN", 5, "Keepsake", "toy, colorful", "4-17-1994", "MARBLES",
				1, "I've lost my marbles!!! They're round and colorful, like marbles. Please please find them!",
				"West Sussex", "SW341A", " 109 Cottage Path Northwest", "England");
		Item dummyItem5 = new Item("SHEPARD", 0, "Miscellaneous", "animal, fluffy, farm", "10-23-2008",
				"SHEEP", 0, "A sheep with fleece as white as snow.", "Arkansas", "32094", "54 Turnip " +
				"Circle, Springdale", "USA");
		Item dummyItem6 = new Item("DOG", 0, "Keepsake", "food, dog, bone", "3-12-2001", "BONE", 0, 
				"bark!!", "Pennsylvania", "19002", "9293 Limekiln Drive, Ambler", "USA");
		Item dummyItem7 = new Item("JACK", "MONEY", 2, "1-29-2013", "Miscellaneous");
		Item dummyItem8 = new Item("DAVID", "WALLET", 1, "2-3-2004", "Miscellaneous");
		Item dummyItem9 = new Item("WALLACE", "COMPUTER", 1, "7-5-2009", "Miscellaneous");
		
		if(UserList!=null) {
			beenCreated = true;
		}
		else{
			UserList = new ArrayList<RegUser>();
			AdminList = new ArrayList<AdminUser>();
			ItemList = new ArrayList<Item>();
		}
		if(!beenCreated) {
			AdminList.add(dummyAdmin);
			UserList.add(dummyUser);
			UserList.add(otherUser);
			ItemList.add(dummyItem0);
			ItemList.add(dummyItem1);
			ItemList.add(dummyItem2);
			ItemList.add(dummyItem3);
			ItemList.add(dummyItem4);
			ItemList.add(dummyItem5);
			ItemList.add(dummyItem6);
			ItemList.add(dummyItem7);
			ItemList.add(dummyItem8);
			ItemList.add(dummyItem9);
		}
		setContentView(R.layout.activity_login);

		// Set up the login form.
		mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
		mEmailView = (EditText) findViewById(R.id.email);
		mEmailView.setText(mEmail);

		mPasswordView = (EditText) findViewById(R.id.password);
		mPasswordView
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {
					@Override
					public boolean onEditorAction(TextView textView, int id,
							KeyEvent keyEvent) {
						if (id == R.id.login || id == EditorInfo.IME_NULL) {
							attemptLogin();
							return true;
						}
						return false;
					}
				});

		mLoginFormView = findViewById(R.id.login_form);
		mLoginStatusView = findViewById(R.id.login_status);
		mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);

		findViewById(R.id.sign_in_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						attemptLogin();
					}
				});
		findViewById(R.id.register_button).setOnClickListener(
				new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						Intent newUserActivity =  new Intent("android.intent.action.NEWUSERACTIVITY");
						startActivity(newUserActivity);
					}
				});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.activity_login, menu);
		return true;
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin() {
		if (mAuthTask != null) {
			return;
		}

		// Reset errors.
		mEmailView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		mEmail = mEmailView.getText().toString();
		mPassword = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password.
		if (TextUtils.isEmpty(mPassword)) {
			mPasswordView.setError(getString(R.string.error_field_required));
			focusView = mPasswordView;
			cancel = true;
		} else if (mPassword.length() < 4) { //password length must be >=5
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(mEmail)) {
			mEmailView.setError(getString(R.string.error_field_required));
			focusView = mEmailView;
			cancel = true;
		} else if (!mEmail.contains("@")) {
			mEmailView.setError(getString(R.string.error_invalid_email));
			focusView = mEmailView;
			cancel = true;
		}

		if (cancel) {
			// There was an error; don't attempt login and focus the first
			// form field with an error.
			focusView.requestFocus();
		} else {
			// Show a progress spinner, and kick off a background task to
			// perform the user login attempt.
			mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
			showProgress(true);
			mAuthTask = new UserLoginTask();
			mAuthTask.execute((Void) null);
		}
	}

	/**
	 * Shows the progress UI and hides the login form.
	 */
	@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
	private void showProgress(final boolean show) {
		// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
		// for very easy animations. If available, use these APIs to fade-in
		// the progress spinner.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
			int shortAnimTime = getResources().getInteger(
					android.R.integer.config_shortAnimTime);

			mLoginStatusView.setVisibility(View.VISIBLE);
			mLoginStatusView.animate().setDuration(shortAnimTime)
					.alpha(show ? 1 : 0)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginStatusView.setVisibility(show ? View.VISIBLE
									: View.GONE);
						}
					});

			mLoginFormView.setVisibility(View.VISIBLE);
			mLoginFormView.animate().setDuration(shortAnimTime)
					.alpha(show ? 0 : 1)
					.setListener(new AnimatorListenerAdapter() {
						@Override
						public void onAnimationEnd(Animator animation) {
							mLoginFormView.setVisibility(show ? View.GONE
									: View.VISIBLE);
						}
					});
		} else {
			// The ViewPropertyAnimator APIs are not available, so simply show
			// and hide the relevant UI components.
			mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
			mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
		}
	}

	/**
	 * Represents an asynchronous login/registration task used to authenticate
	 * the user.
	 */
	public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
		View focusView = null;
		boolean locked = false;
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO: attempt authentication against a network service.
			
			try {
				// Simulate network access.
				Thread.sleep(10);
			} catch (InterruptedException e) {
				return false;
			}
			for (AdminUser attempt : AdminList) {
				if(attempt.checkCredentials(mEmail, mPassword)){
					Intent adminHomeActivity =  new Intent("android.intent.action.ADMINHOMEACTIVITY");
					startActivity(adminHomeActivity);
					return true;
				}
			}
			/**
			 * Iterates through the User list, checking the inputted e-mail and password for each, and if a login attempt is successful, goes to a new regular user home activity
			 */
			for (RegUser attempt : UserList) {
				locked = false;
				if(attempt.checkCredentials(mEmail, mPassword)){
					if(!attempt.isLocked)
					{
						loggedIn = attempt;
						Intent regHomeActivity =  new Intent("android.intent.action.REGHOMEACTIVITY");
						startActivity(regHomeActivity);
						attempt.loginCount = 0;
						return true;
					}
					else {
						locked = true;
						return false;
					}
				}
			}
			return false;
		}
		
		@Override
		protected void onPostExecute(final Boolean success) {
			mAuthTask = null;
			showProgress(false);

			if (success) {
				finish();
			} else {
				if(locked == true){
					mEmailView.setError(getString(R.string.error_account_locked));
					mEmailView.requestFocus();
					return;
				}
				else {
					mPasswordView.setError(getString(R.string.error_incorrect_password));
					mPasswordView.requestFocus();
				}
			}
		}

		@Override
		protected void onCancelled() {
			mAuthTask = null;
			showProgress(false);
		}
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onBackPressed()
	 */
	@Override
	public void onBackPressed() {
		super.onDestroy();
	}
}
